<!-- eslint-disable vue/multi-word-component-names -->
<template>
  <div class="body">
    <!-- 查询部分 -->
    <el-row :span="24" class="top">
      <el-form ref="form" :model="form" class="query">
        <el-form-item label="工单编号 :">
          <el-input
            v-model="form.taskCode"
            placeholder="请输入"
            :clearable="true"
          ></el-input>
        </el-form-item>
        <el-form-item label="工单状态 :">
          <el-select
            v-model="form.status"
            placeholder="请选择"
            :clearable="true"
          >
            <el-option
              v-for="item in allTaskStatus"
              :key="item.statusId"
              :label="item.statusName"
              :value="item.statusId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="query">
            <i class="el-icon-search"></i> 搜索
          </el-button>
        </el-form-item>
      </el-form>
    </el-row>
    <!-- 列表部分 -->
    <el-row :span="24" class="content">
      <!-- 头部按钮 -->
      <div class="title">
          <el-button
          type="warning"
          icon="el-icon-circle-plus-outline"
          size="medium"
           @click="addFormVisible = true"
          >新建</el-button>
        <el-button @click="configVisible = true"  type="warning" class="pink">
          工单配置
        </el-button>
      </div>
      <!-- 列表 -->
      <div class="list">
        <taskList
          v-loading="loading"
          :tableList="tableList"
          :pageIndex="searchData.pageIndex"
          @look="look"
        />
      </div>
      <!-- 分页 -->
      <!-- <div class="page">
        <div class="left">
          共{{ tableData.totalCount }}条记录&emsp;第
          {{ searchData.pageIndex }}/{{ tableData.totalPage }}页
        </div>
        <div class="right">
          <div @click="upData(-1)" :class="{ allow: searchData.pageIndex > 1 }">
            上一页
          </div>
          <div
            @click="upData(1)"
            :class="{ allow: searchData.pageIndex < tableData.totalPage }"
          >
            下一页
          </div>
        </div>
      </div> -->
      <bommtom
        :pageIndex="searchData.pageIndex"
        :tableData="tableData"
        @change="upData"
      />
    </el-row>
    <!-- 弹出框 -->
    <!-- 新建 -->
    <el-dialog title="新增工单" :visible.sync="addFormVisible">
      <el-form :model="addForm" size="mini" :rules="rules" ref="add">
        <el-form-item label="设备编号:" prop="innerCode">
          <el-input
            v-model="addForm.innerCode"
            autocomplete="off"
            placeholder="请输入设备编号"
            maxlength="15"
            show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item label="工单类型:" prop="productType">
          <el-select v-model="addForm.productType" placeholder="请选择活动区域">
            <el-option
              v-for="item in allTaskStatusFliter"
              :key="item.typeId"
              :label="item.typeName"
              :value="+item.typeId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="补货数量:">
          <el-dialog
            width="30%"
            title="补货详情"
            :visible.sync="addInnerVisible"
            append-to-body
          >
            <div class="replenish">
              <replenishList :channelList="channelList" />
            </div>
            <div slot="footer" class="dialog-footer">
              <el-button class="pink" @click="replenish">取 消</el-button>
              <el-button
                class="orange"
                type="primary"
                @click="addInnerVisible = false"
                >确 定</el-button
              >
            </div>
          </el-dialog>
          <div class="blue" @click="showInner">
            <i class="el-icon-edit-outline"></i>补货清单
          </div>
        </el-form-item>
        <el-form-item label="运营人员:" prop="assignorId">
          <el-select v-model="addForm.assignorId" placeholder="请选择运营人员">
            <el-option
              v-for="item in operatorList"
              :key="item.userId"
              :label="item.userName"
              :value="+item.userId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注:" prop="desc">
          <el-input
            type="textarea"
            v-model="addForm.desc"
            placeholder="请输入备注 (不超过40字)"
            maxlength="40"
            show-word-limit
          ></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button class="pink" @click="addFormVisible = false"
          >取 消</el-button
        >
        <el-button class="orange" type="primary" @click="add">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 工单配置 -->
    <el-dialog title="工单配置" :visible.sync="configVisible">
      <el-form label-width="100px" class="demo-ruleForm">
        <el-form-item
          class="config"
          label="补货警戒线："
          label-width="200"
          :rules="[{ required: true, message: '不能为空' }]"
        >
          <el-input-number
            v-model="configNumber"
            controls-position="right"
            :max="100"
            :min="1"
          ></el-input-number> </el-form-item
      ></el-form>
      <div slot="footer" class="dialog-footer">
        <el-button class="pink" @click="configVisible = false">取 消</el-button>
        <el-button class="orange" type="primary" @click="config"
          >确 定</el-button
        >
      </div>
    </el-dialog>

    <!-- 工单详情 -->
    <el-dialog title="工单详情" :visible.sync="detailsVisible" class="details">
      <!-- 取消 -->
      <template v-if="taskInfo.taskStatus === 3">
        <div class="task-status">
          <img
            src=""
            class="icon"
          /><span class="status">取消</span
          ><img
            src="http://likede2-admin.itheima.net/img/pic_3.e8208e34.png"
            class="pic"
          />
        </div>
        <div class="content">
          <el-col :span="12">设备编号：&emsp;{{ taskInfo.innerCode }}</el-col>
          <el-col :span="12">创建日期：&emsp;{{ taskInfo.createTime }}</el-col>
          <el-col :span="12">取消日期：&emsp;{{ taskInfo.updateTime }}</el-col>
          <el-col :span="12">运营人员：&emsp;{{ taskInfo.userName }}</el-col>
          <el-col :span="12"
            >工单类型：&emsp;{{
              taskList[taskInfo.productTypeId].typeName
            }}</el-col
          >
          <el-col :span="12"
            >补货数量：&emsp;<span
              class="blue"
              @click="replenishShow(taskInfo.taskId)"
              >补货详情</span
            ></el-col
          >
          <el-col :span="12"
            >工单方式：&emsp;{{ taskInfo.createType ? "手动" : "自动" }}</el-col
          >
          <el-col :span="12">取消原因：&emsp;{{ taskInfo.expect }}</el-col>
        </div>
      </template>
      <!-- 待办 -->
      <template v-if="taskInfo.taskStatus === 1">
        <div class="task-status">
          <img
            src=""
            class="icon"
          /><span class="status">取消</span
          ><img
            src="http://likede2-admin.itheima.net/img/pic_1.834b274c.png"
            class="pic"
          />
        </div>
        <div class="content">
          <el-col :span="12">设备编号：&emsp;{{ taskInfo.innerCode }}</el-col>
          <el-col :span="12">创建日期：&emsp;{{ taskInfo.createTime }}</el-col>
          <el-col :span="12">运营人员：&emsp;{{ taskInfo.userName }}</el-col>
          <el-col :span="12"
            >工单类型：&emsp;{{
              taskList[taskInfo.productTypeId].typeName
            }}</el-col
          >
          <el-col :span="12"
            >补货数量：&emsp;<span
              class="blue"
              @click="replenishShow(taskInfo.taskId)"
              >补货详情</span
            ></el-col
          >
          <el-col :span="12"
            >工单方式：&emsp;{{ taskInfo.createType ? "手动" : "自动" }}</el-col
          >
          <el-col :span="12">备注&emsp;{{ taskInfo.desc }}</el-col>
        </div>
      </template>
      <!-- 补货详情 -->
      <el-dialog
        width="30%"
        title="补货详情"
        :visible.sync="replenishVisible"
        append-to-body
      >
        <div class="replenish">
          <replenishList :channelList="channelList" :isReplenish="false" />
        </div>
      </el-dialog>
      <div slot="footer" class="dialog-footer">
        <el-button class="pink" @click="close">{{
          taskInfo.taskStatus === 1 ? "取消" : "重新创建"
        }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import bommtom from './components/footer.vue'
import replenishList from './components/text.vue'
import taskList from './components/lisk.vue'
import {
  allTaskStatus,
  getTaskList,
  taskSearch,
  createTask,
  supplyAlertValue,
  autoSupplyConfig,
  taskInfo,
  taskDetails,
  cancel,
  operatorList,
  channelList
} from '@/api/Workorder/operation'

export default {
  components: {
    taskList,
    replenishList,
    bommtom
  },
  data () {
    return {
      form: {
        taskCode: '',
        status: ''
      },
      addForm: {
        assignorId: '',
        createType: 1,
        desc: '',
        details: [],
        innerCode: '',
        productType: '',
        userId: 1
      },
      rules: {
        innerCode: { required: true, message: '请输入设备编号' },
        productType: { required: true, message: '请输入工单类型' },
        assignorId: { required: true, message: '请输入运营人员' },
        desc: { required: true, message: '请输入备注' }
      },
      loading: true,
      // 请求列表数据内容
      searchData: {
        pageIndex: 1,
        pageSize: 10,
        isRepair: false
      },
      allTaskStatus: [],
      taskList: [],
      tableData: {},
      tableList: [],
      addFormVisible: false,
      addInnerVisible: false,
      configVisible: false,
      detailsVisible: false,
      replenishVisible: false,
      operatorList: [],
      channelList: [],
      configNumber: 1,
      taskInfo: {},
      taskDetails: [],
      timer: null
    }
  },
  created () {
    // 用 .then 同时发送 ajax
    allTaskStatus().then((res) => {
      this.allTaskStatus = res
    })
    getTaskList().then((res) => {
      this.taskList = res
    })
    taskSearch(this.searchData).then((res) => {
      this.tableData = res
      this.tableList = res.currentPageRecords
      this.loading = false
    })
  },
  watch: {
    'addForm.innerCode': function () {
      // 为空不发送请求, .5s节流
      if (this.addForm.innerCode) {
        clearTimeout(this.timer)
        this.timer = setTimeout(async () => {
          this.operatorList = await operatorList(this.addForm.innerCode)
        }, 500)
      }
    },
    addFormVisible () {
      if (!this.addFormVisible) {
        this.$refs.add.resetFields()
      }
    },
    async addInnerVisible () {
      if (this.addInnerVisible) {
        const res = await channelList(this.addForm.innerCode)
        this.channelList = res
          .filter((i) => i.sku)
          .map((i) => ({
            channelCode: i.channelCode,
            skuName: i.sku && i.sku.skuName,
            skuImage: i.sku && i.sku.skuImage,
            skuId: i.sku.skuId,
            currentCapacity: i.currentCapacity,
            expectCapacity: i.maxCapacity - i.currentCapacity
          }))
        this.channelList.forEach(i => {
          i.max = i.expectCapacity
        })
      }
    },
    async configVisible () {
      if (this.configVisible) this.configNumber = await supplyAlertValue()
    }
  },
  computed: {
    allTaskStatusFliter () {
      return this.taskList.filter((i) => i.type === 2)
    }
  },
  methods: {
    async query () {
      this.searchData = {
        pageIndex: 1,
        pageSize: 10,
        isRepair: false,
        ...this.form
      }
      const res = await taskSearch({ ...this.searchData })
      this.tableData = res
      this.tableList = res.currentPageRecords
    },
    add () {
      this.$refs.add.validate(async (valid) => {
        if (valid) {
          try {
            this.addForm.details = this.channelList.map((i) => ({
              channelCode: i.channelCode,
              expectCapacity: i.expectCapacity,
              skuId: i.skuId,
              skuName: i.skuName
            }))
            const res = await createTask(this.addForm)
            console.log(res)
            this.$message.success('新建成功')
          } catch (error) {
            this.$message.error(error.response.data)
          }
          this.addFormVisible = false
        }
      })
    },
    async config () {
      this.configVisible = false
      await autoSupplyConfig({ alertValue: this.configNumber })
      this.searchData = {
        pageIndex: 1,
        pageSize: 10,
        isRepair: false
      }
      taskSearch({ ...this.searchData })
    },
    async replenish () {
      this.addInnerVisible = false
      const res = await channelList(this.addForm.innerCode)
      console.log(res)
      this.addForm.details = res.map((i) => ({
        channelCode: i.channelCode,
        skuName: i.sku && i.sku.skuName,
        skuImage: i.sku && i.sku.skuImage,
        currentCapacity: i.currentCapacity,
        expectCapacity: i.maxCapacity - i.currentCapacity
      }))
    },
    showInner () {
      this.$refs.add.validateField('innerCode', (valid) => {
        if (!valid) {
          this.addInnerVisible = true
        }
      })
    },
    async look (id) {
      this.detailsVisible = true
      this.taskInfo = await taskInfo(id)
    },
    async replenishShow (id) {
      // 补货详情页
      this.replenishVisible = true
      this.channelList = await taskDetails(id)
    },
    close () {
      console.log(this.taskInfo)
      if (this.taskInfo.taskStatus === 1) {
        // 代办
        this.$confirm('确认取消？')
          .then(async (_) => {
            this.detailsVisible = false
            // 清除当前项
            await cancel({ taskId: this.taskInfo.taskId, desc: '' })
            // 清空请求项并重新请求数据
            this.searchData = {
              pageIndex: 1,
              pageSize: 10,
              isRepair: false
            }
            const res = await taskSearch({
              ...this.searchData
            })
            this.tableData = res
            this.tableList = res.currentPageRecords
          })
          .catch((_) => {})
      } else if (this.taskInfo.taskStatus === 3) {
        // 重新创建
        this.addForm = {
          assignorId: '',
          createType: 1,
          desc: '',
          details: [],
          innerCode: this.taskInfo.innerCode,
          productType: '',
          userId: 1
        }
        this.addFormVisible = true
      }
    },
    async upData (num) {
      // 判断页数是否合规
      this.loading = true
      this.searchData.pageIndex += num
      const res = await taskSearch({ ...this.searchData })
      this.tableData = res
      this.tableList = res.currentPageRecords
      this.loading = false
    }
  }
}
</script>

<style lang="scss" scoped>
.body {
  padding: 10px;
  & > .el-row {
    background-color: #fff;
    &.top {
      height: 64px;
      margin-bottom: 20px;
      .query {
        display: flex;
        width: 1200px;
        height: 100%;
        padding-left: 30px;
        .el-form-item {
          display: flex;
          align-items: center;
          width: 300px;
          margin: 0;
          div {
            width: 206px;
            height: 36px;
            ::v-deep input {
              height: 36px;
            }
          }
          .el-button {
            display: flex;
            justify-content: center;
            align-items: center;
            min-width: 80px;
            height: 36px;
            padding: 0;
            background-color: #5f84ff;
            border: none;
          }
        }
      }
    }
    &.content {
      padding: 20px;
      .title {
        margin-bottom: 20px;
      }
      // .page {
      //   display: flex;
      //   justify-content: space-between;
      //   align-items: center;
      //   height: 80px;
      //   color: #dbdfe5;
      //   font-size: 16px;
      //   .right {
      //     display: flex;
      //     justify-content: space-around;
      //     width: 200px;
      //     margin-right: 10px;
      //     div {
      //       width: 70px;
      //       height: 32px;
      //       background-color: #edf0f9;
      //       border-radius: 3px;
      //       text-align: center;
      //       line-height: 32px;
      //       cursor: not-allowed;
      //       &.allow {
      //         background-color: #d5ddf8;
      //         color: #666;
      //         cursor: pointer;
      //       }
      //     }
      //   }
      // }
    }
  }
}
.replenish {
  overflow: scroll;
  width: 580px;
  height: 313px;
  margin-left: -70px;
}

.el-dialog__wrapper {
  ::v-deep .el-dialog {
    width: 666.5px !important;
    border-radius: 10px;
    .el-dialog__body {
      padding: 0 100px;
      .el-form-item__label {
        width: 82px;
      }
      .el-input,
      .el-textarea {
        width: 346px;
      }
    }
    .dialog-footer {
      display: flex;
      justify-content: space-evenly;
      padding: 0 150px;
    }
  }
}
.config {
  ::v-deep .el-form-item__label {
    width: 110px !important;
  }
  .el-input-number {
    width: 346px;
  }
}
.details {
  ::v-deep .el-dialog__body {
    padding: 20px !important;
  }
  .task-status {
    display: flex;
    align-items: center;
    height: 54px;
    margin-bottom: 25px;
    background-color: hsla(0, 0%, 92.5%, 0.39);
    .icon {
      margin: 0 20px;
    }
    span {
      flex: 1;
    }
    .pic {
      margin-right: 76px;
      margin-bottom: 7px;
    }
  }
  .content {
    overflow: hidden;
    .el-col {
      height: 36px;
      padding-left: 50px;
    }
  }
}
</style>
